package com.example.bookmall.controller.userSystem;


import com.example.bookmall.entity.Result;
import com.example.bookmall.entity.usercore.PwdString;
import com.example.bookmall.entity.usercore.UpdateData;
import com.example.bookmall.entity.usercore.User;
import com.example.bookmall.service.UserService;
import com.example.bookmall.utils.AliOssUtil;
import com.example.bookmall.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    //TODO:用户个人信息

    @Autowired
    private UserService userService;

    //获取用户信息
    @GetMapping("/show")
    public Result showUserInfo() {

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        User currentuser = userService.findById(userId);

        return Result.success(currentuser);

    }

    //注销
    @GetMapping("/logout")
    public Result logout() {
        ThreadLocalUtil.remove();
        return Result.success("注销成功");
    }

    //修改当前用户基本资料  用户昵称 手机号码 邮箱 性别
    @PostMapping("/updateUser")
    public Result updateUserProfile(@RequestBody UpdateData updateData) {
        //更新用户信息
        return userService.updateUserProfile(updateData);

    }


    //修改用户密码  旧密码 新密码 确认新密码
    @PostMapping("/updatePwd")
    public Result updatPwd(@RequestBody PwdString pwdString, @RequestHeader("Authorization") String token){
        return userService.updatePwd(pwdString,token);
    }


    @PostMapping("/avatar")
    public Result<String> upload(MultipartFile file) throws Exception {

        if (file.isEmpty()||!file.getContentType().startsWith("image")){
            return Result.error("仅支持图片文件");
        }

        //originalFilename是原始文件的名字
        String originalFilename = file.getOriginalFilename();

        //保证文件的名字是唯一的，从而防止文件的覆盖
        String filename= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));

        String url = AliOssUtil.uploadFile(filename, file.getInputStream());

        //当前用户
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        userService.updateAvatar(url,userId);


        return Result.success(url);
    }
}

